package com.ops.uitl.tapestry;


import com.ops.uitl.common.Common;
import org.apache.log4j.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

public class AppServlet extends HttpServlet {

	protected Logger log = Logger.getLogger(this.getClass());
	protected Common common = Common.getInstance();

	private HttpServletRequest request;
	private HttpServletResponse response;
	private PageData pd;

	/**
	 * get visit
	 * @return Object
	 * @throws Exception
	 */
	public Object getVisit() throws Exception {
		AppEngine engine = (AppEngine) request.getSession().getAttribute("org.apache.tapestry.engine:" + common.getProperty("project/name"));
		if (engine == null) return new AppContext();
		return engine.getVisit();
	}

	/**
	 * redirect to
	 * @param page
	 * @throws Exception
	 */
	public void redirectTo(String page) throws Exception {
		RequestDispatcher dispatcher = request.getRequestDispatcher(page);
		dispatcher.forward(request, response);
	}

	/**
	 * get writer
	 * @throws IOException
	 */
	public PrintWriter getWriter() throws IOException {
		return response.getWriter();
	}

	/**
	 * set error info
	 * @param throwable
	 */
	public void setErrorInfo(Throwable throwable) {
		try {
			response.setContentType("text/html;charset=GBK");
			PrintWriter out = response.getWriter();
			String message = throwable.getMessage();
			if ("java.lang.RuntimeException".equals(throwable.getClass().getName())) {
				message = message.substring(message.lastIndexOf(":") + 1).trim();
			}
			message = message.replaceAll("\\n", "\\\\n");
			message = message.replaceAll("\\\"", "\\\\\"");

			out.println("<script>");
			out.println("	alert(\"错误提示：" + message + "\\n点【确定】返回到主页面\");");
			out.println("	top.window.document.getElementById(\"PopupAgent\") != null ? window.close() : history.back();");
			out.println("</script>");
		} catch (Exception e) {
			log.error(e);
		}
	}

	/**
	 * servlet init
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void servletInit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("GBK");
		synchronized(this) {
			this.request = request;
			this.response = response;
		}
	}

	/**
	 * exist page data
	 * @return boolean
	 */
	public boolean existPageData() {
		return pd != null;
	}

	/**
	 * get page data
	 * @return PageData
	 * @throws Exception
	 */
	public PageData getPageData() throws Exception {
		synchronized(this) {
			if (pd == null) {
				pd = new PageData(request);
			} else {
				Map connItems = pd.getDBConns();
				pd = new PageData(request);
				pd.setDBConns(connItems);
			}
			pd.setContext((AppContext) getVisit());
		}
		return pd;
	}

	/**
	 * servlet reseted
	 * @param event
	 */
	public void servletReseted() {
		if (existPageData()) {
			try {
				synchronized(this) {
					pd.rollbackConnections();
				}
			} catch (Exception e) {
				log.error(e);
			}
		}
	}

	/**
	 * servlet detached
	 * @param event
	 */
	public void servletDetached() {
		if (existPageData()) {
			try {
				synchronized(this) {
					pd.cleanupConnections();
				}
			} catch (Exception e) {
				log.error(e);
			}
		}
	}

}